<template>
    <div class="e-form">
        <BillTop @cancel="handleClose"></BillTop>
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="领料明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form
                                :model="basicForm"
                                :label-width="formLabelWidth"
                                ref="ruleForm"
                                :rules="rules"
                                class="demo-ruleForm"
                            >
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="领料编号：">
                                            <span>{{ basicForm.billNo }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="机构：">
                                            <span>{{ basicForm.orgName }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="业务类型："
                                            prop="businessTypeKey"
                                        >
                                            <el-select
                                                v-model="
                                                    basicForm.businessTypeKey
                                                "
                                                @change="businessTypeChenge"
                                            >
                                                <el-option
                                                    v-for="item in receiveBusinessType"
                                                    :key="item.id"
                                                    :value="item.id"
                                                    :label="item.uname"
                                                ></el-option>
                                            </el-select>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="发料人员：">
                                            <span>
                                                {{
                                                    basicForm.providePersonName
                                                }}
                                            </span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="领料单位："
                                            prop="receiveCompanyName"
                                        >
                                            <el-input
                                                v-model="
                                                    basicForm.receiveCompanyName
                                                "
                                                readonly
                                            >
                                                <i
                                                    slot="suffix"
                                                    class="
                                                        el-input__icon
                                                        el-icon-document-copy
                                                    "
                                                    @click="clickCompany"
                                                ></i>
                                            </el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="领料人员："
                                            prop="receivePersonName"
                                        >
                                            <el-input
                                                readonly
                                                v-model="
                                                    basicForm.receivePersonName
                                                "
                                            >
                                                <i
                                                    slot="suffix"
                                                    class="
                                                        el-input__icon
                                                        el-icon-document-copy
                                                    "
                                                    @click="returnPersonnelName"
                                                ></i>
                                            </el-input>
                                            <el-button
                                                type="primary"
                                                style="
                                                    background: #2e61d7;
                                                    margin-left: 5px;
                                                "
                                                @click="AddPersonnelName"
                                                >添加乙方人员</el-button
                                            >
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="合同：">
                                            <el-input
                                                readonly
                                                v-model="basicForm.contractName"
                                            ></el-input>
                                            <el-button
                                                class="a"
                                                @click="linkContract"
                                                >查看</el-button
                                            >
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="领料日期："
                                            prop="receiveDate"
                                        >
                                            <el-date-picker
                                                value-format="yyyy-MM-dd"
                                                :clearable="false"
                                                type="date"
                                                placeholder="选择日期"
                                                v-model="basicForm.receiveDate"
                                            ></el-date-picker>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item label="领料数量：">
                                            <span>{{
                                                basicForm.receiveQuantity
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item label="状态：">
                                            <span>{{
                                                statusLable(basicForm.state)
                                            }}</span>
                                        </el-form-item>
                                    </el-col>
                                </el-row>

                                <el-row>
                                    <el-col :span="24">
                                        <el-form-item label="备注：">
                                            <el-input
                                                type="textarea"
                                                v-model="basicForm.remarks"
                                                autocomplete="off"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                            </el-form>
                        </div>
                    </div>
                    <!-- 领料明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">领料明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <el-button
                                        size="mini"
                                        type="primary"
                                        @click="clickStock"
                                        >选择库存</el-button
                                    >
                                </div>
                            </div>

                            <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <el-table
                                class="table"
                                :data="detailedTableDataComputed"
                                border
                                style="width: 100%"
                                default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                row-key="uuid"
                                 :max-height="$store.state.tableHeight"
                                :row-class-name="tableRowClassName"
                                ref="table"
                                 v-sortTable="{ 'tableData': detailedTableDataComputed, '_this': this, 'ref': 'table' }"
                            >
                                <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >
                                <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div style="cursor: pointer">
                                                <img
                                                v-if="$index > 0"
                                                    src="@/assets/btn/delete.png"
                                                    @click="
                                                        deleteEle(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >
                                    <!-- <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-if="$index > 0"
                                            v-model="row.texture"
                                            clearable
                                            @input="curStateChange(row)"
                                        ></el-input>
                                    </template> -->
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="warehouseName"
                                    label="仓库"
                                    width="200"
                                >
                                    <!-- <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-if="$index > 0"
                                            v-model="row.warehouseName"
                                            clearable
                                            @input="curStateChange(row)"
                                        ></el-input>
                                    </template> -->
                                </el-table-column>
                                <el-table-column
                                    prop="source"
                                    label="来源"
                                    width="200"
                                >
                                <template slot-scope="{row,$index}">
                                    <span   v-if="$index > 0">
                                        {{
                                            row.source==1?'自购':
                                              row.source==2?'调入':
                                                row.source==3?'外租':
                                                '内租'
                                        }}
                                    </span>
                                </template>
                                </el-table-column>
                                <el-table-column
                                    prop="inventoryQuantity"
                                    label="库存数量"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="pickingWarehouseName"
                                    label="领料单位仓库"
                                    width="200"
                                >
                                    <template slot="header">
                                        <span>领料单位仓库</span>
                                        <i
                                            slot="suffix"
                                            class="
                                                el-input__icon
                                                el-icon-document-copy
                                            "
                                            style="cursor: pointer"
                                            @click="selectWarehouse"
                                        ></i>

                                    </template>
                                </el-table-column>
                                <el-table-column
                                    v-if="
                                        basicForm.businessTypeKey == 1 ||
                                        basicForm.businessTypeKey == 4
                                    "
                                    prop="subItem"
                                    label="分部分项"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="timeUnit"
                                    label="计时单位"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-select
                                            v-model="row.timeUnit"
                                            placeholder="请选择"
                                            @change="curStateChange(row)"
                                            v-if="$index > 0"
                                        >
                                            <el-option
                                                v-for="item in timeUnitList"
                                                :key="item.value"
                                                :label="item.label"
                                                :value="item.label"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="usageTime"
                                    label="使用时间"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                            v-if="$index > 0"
                                            v-enter-float="{
                        set: row,
                        key: 'usageTime',
                      }"
                                            v-model="row.usageTime"
                                        ></el-input>
                                    </template>
                                </el-table-column>

                                <el-table-column
                                    prop="receivedQuantity"
                                    label="领用数量"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-input
                                        v-enter-float2="{
                                            set: row,
                                            key: 'receivedQuantity'
                                        }"
                                            v-if="$index > 0"
                                            v-model="row.receivedQuantity"
                                            @input="curStateChange(row)"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="supplyType"
                                    label="甲供类型"
                                    width="200"
                                >
                                    <template slot-scope="{ row, $index }">
                                        <el-select
                                            v-if="$index > 0"
                                            v-model="row.supplyType"
                                            @change="curStateChange(row)"
                                        >
                                            <el-option
                                                v-for="item in supplyTypeArr"
                                                :key="item.id"
                                                :label="item.name"
                                                :value="item.id"
                                            >
                                            </el-option>
                                        </el-select>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="remainingInventory"
                                    label="库存剩余"
                                    width="200"
                                >
                                </el-table-column>
                            </el-table>
                            <!-- <span>
                                {{
                                    test
                                }}
                            </span> -->
                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">照片信息</div>
                        <attach-comp
                            :relationId="attachId"
                            bucketName="turnover"
                        />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6077"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
        <div class="buttons">
            <span class="tip"
                ><span style="color: red; margin-right: 0">*</span
                >为必填项</span
            >

            <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId" />
            <el-button size="small" @click="handleClose">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import { mapState } from 'vuex'
import auditRequest from '@/api/turnover/audit.js'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'
import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit, deleteLogic, detailedTableDataComputed } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import { showLoading, hideLoading } from '@/utils/common'

import otherRequest from '@/api/turnover/other.js'
import {
    setSelectStock,
    subcontract,
    personnelOfPartyB,
    GeneralSelectOuter
} from '@/api/turnover/ppw.js'
import { getUuid, openAppClient, selectDataClient } from '@/utils/common'
import { mapMutations } from 'vuex'
import $ from 'jquery'

import '@/utils/jquery.scrollTo.min'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.billId
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList, //计时单位
            receiveBusinessType: state =>
                state.turnover.turnoverData.receiveBusinessType
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        detailedTableDataComputed () {
            return detailedTableDataComputed(this.detailedTableData)
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData => {
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM => {
                const { childNodes } = DOM
                if (childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item => {
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        }
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = ['baseInfo', 'detailed', 'attach', 'auditHistory']
        this.tabArr = arr //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })

        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    created () {
        this.billId = this.$route.query.billid
        this.getCurrentUnitInfo()
        this.getBasicInfo()
        this.getDicValue()
        this.getDtlList()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                baseCurId: '',
                baseCurMoney: 0,
                baseCurName: '',
                baseCurRate: 0,
                billId: '',
                billNo: '',
                businessTypeKey: '',
                businessTypeValue: '',
                contractAmount: 0,
                contractId: '',
                contractName: '',
                contractNo: '',
                contractType: 0,
                currency: '',
                nullifyCreated: '',
                nullifyCreator: '',
                nullifyCreatorId: '',
                nullifyDescription: '',
                nullifyReason: '',
                orgId: '',
                orgName: '',
                providePersonId: '',
                providePersonName: '',
                receiveAmountMoney: 0,
                receiveCompanyId: '',
                receiveCompanyName: '',
                receiveDate: '',
                receivePersonId: '',
                receivePersonName: '',
                receiveQuantity: 0,
                remarks: '',
                returnQuantity: 0,
                state: 0
            },
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: []
            },
            formLabelWidth: '150px',
            detailedTableData: [], //领料缪明细
            detailedTableDataCopy: [], //绑定页面上的明细
            changeTableData: [], //变更信息
            basicInfo: {},
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            MouseEnterId: 0,
            rules: {
                businessTypeKey: [
                    {
                        required: true,
                        message: '请选择业务类型',
                        trigger: 'chenge'
                    }
                ],
                // receiveCompanyName: [
                //     {
                //         required: true,
                //         message: '请选择领料单位',
                //         trigger: 'chenge'
                //     }
                // ],
                receiveDate: [
                    {
                        required: true,
                        message: '请选择日期',
                        trigger: 'chenge'
                    }
                ],
                // receivePersonName: [
                //     {
                //         required: true,
                //         message: '请选择领料人员'
                //     }
                // ]
            },
            businessType: [
                {
                    id: '1',
                    uname: '分包合同'
                },
                {
                    id: '2',
                    uname: '加工合同'
                },
                {
                    id: '3',
                    uname: '销售合同'
                },
                {
                    id: '4',
                    uname: '事实合同'
                },
                {
                    id: '5',
                    uname: '自行加工'
                }
            ],
            supplyTypeArr: [
                {
                    id: 0,
                    name: '工程消耗'
                },
                {
                    id: 1,
                    name: '研发支出'
                },
                {
                    id: 2,
                    name: '环保支出'
                }
            ],
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6077,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            auditState: {},
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            curRow: {},
            test: []
        }
    },
    methods: {
        ...mapMutations(['setSelectedInfo']),

        //获取当前使用的字典
        getDicValue () {
            this.$store.dispatch('equip/setTimeUnitList') //更新计时单位
        },
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/receive/findById',
                    params: {
                        billId: this.billId
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    res.isShare == 1
                        ? (res.isShare = true)
                        : (res.isShare = false)

                    for (let key in res) {
                        this.basicForm[key] = res[key]
                    }
                })
        },
        // 获取明细
        getDtlList () {
            otherRequest.turnoverReceiveFindByBillId(this.billId).then(res => {
                if (res.length > 0) {
                    res.forEach(item => {
                        item.materialClassName = item.topClassName
                        item.uuid = getUuid()

                        item.children.forEach(i => {
                            i.parentId = item.uuid
                            i.uuid = i.dtlId
                            i.changeType = 0
                        })

                        const count = item.children.reduce(
                            (prev, c) => (prev += c.receivedQuantity || 0),
                            0
                        )
                        item.materialName = `小计： ${count}`
                    })

                    this.detailedTableData = res
                    this.detailedTableDataCopy = JSON.parse(JSON.stringify(res))
                    this.collectCount()
                }
            })
        },
        async clickCompany () {
            if (!this.basicForm.businessTypeKey) {
                this.clientPop('err', '请先选业务类型！')
                return
            }
            // 事实合同
            if (
                this.basicForm.businessTypeKey == '4' ||
                this.basicForm.businessTypeKey == '5'
            ) {
                let type
                let businessTypes = []
                this.basicForm.businessTypeKey == '4'
                    ? (type = [3])
                    : ((type = [2]), businessTypes = [5, 7])
                GeneralSelectOuter(type, businessTypes).then(res => {
                    this.basicForm.receiveCompanyName = res.outerName
                    this.basicForm.receiveCompanyId = res.id
                    return
                })
            } else {
                subcontract(this.basicForm.businessTypeKey).then(res => {
                    this.test = res
                    // { "contractAmount": 10120, "contractName": "ty测试", "contractNumber": "SRBCFBHT057", "contractType": 1, "secondPartyId": "1522783844445122561", "secondPartyName": "四川公路桥梁建设集团有限公司江习古高速公路项目经理部TJ4分部", "contractId": "1534855327300407297" }
                    this.basicForm.receiveCompanyName = res.secondPartyName
                    this.basicForm.receiveCompanyId = res.secondPartyId
                    this.basicForm.contractName = res.contractName
                    this.basicForm.contractId = res.contractId
                    this.basicForm.contractAmount = res.contractAmount
                    this.basicForm.contractNo = res.contractNumber
                    if (this.basicForm.businessTypeKey == 4 || this.basicForm.businessTypeKey == 5 ) {
                        this.basicForm.contractType = res.contractType
                    }
                })
            }
        },
        //选择领料单位仓库  //批量
        selectWarehouse () {
            if (!this.basicForm.receiveCompanyName) {
                this.clientPop('err', '请先选择领料单位！')
                return
            }
            selectDataClient({
                SelectServiceToken: '/material/warehouseManagement/listBySubcontractorId', // 客户端对应方法名
                IsSingleMode: false, // 是否单选 true 单选 false 多选
                SelectedIDs: [], // 已选中id(注意：是上一次已选中的id，不是要传的参数，如果第一次选，则传[])
                InitParamsStr: JSON.stringify({
                    orgId: this.basicForm.orgId,
                    subcontractorId: this.basicForm.receiveCompanyId
                }),
                Title: '选择仓库', // 标题
            })
                .then(val=>{
                    let detailedTableDataDeep = [...this.detailedTableData]

                    val.forEach(b=>{
                        detailedTableDataDeep.forEach(item=>{
                            item.children.forEach(a=>{
                                if(a.changeType === 1) {
                                    a.changeType = 1
                                }else{
                                    a.changeType = 2
                                }
                                a.pickingWarehouseId = b.billId
                                a.pickingWarehouseName = b.name
                            })
                        })
                    })

                    this.detailedTableData = detailedTableDataDeep

                })
        },
        clickStock () {
            setSelectStock(this.detailedTableData, this.billId, '2').then(
                res => {
                    // 保存用户选择返回数据到store
                    // this.setSelectedInfo(res.data)
                    // // 客户端弹窗预览结果
                    // // 参数依次为: 打开页面地址、标题、回调函数
                    // openAppClient('/showSelectedData', '选择结果', function () {
                    //     // alert('关闭后回调')
                    // })
                    this.detailedTableData = res.detailedTableData
                }
            )
        },
        // 选领料料人员
        async returnPersonnelName () {
            this.test = this.basicForm.receiveCompanyId
            // this.test =  this.basicForm.receiveCompanyId
            if (!this.basicForm.receiveCompanyId) {
                this.clientPop('err', '请先选择领料单位！')
                return
            }
            this.test = this.basicForm.receiveCompanyId
            const data = await personnelOfPartyB(
                this.basicForm.receiveCompanyId + ''
            )
            this.basicForm.receivePersonId = data.dtlId
            this.basicForm.receivePersonName = data.name
        },
        //添加乙方人员
        AddPersonnelName () {
            openAppClient(
                '/materialPartBPerson',
                '添加乙方人员',
                function () {}
            )
        },
        // 查看合同
        linkContract () {
            if (!this.basicForm.contractId) {
                this.clientPop('err', '请选择领料单位')
                return
            }
            if (
                this.basicForm.receiveCompanyId == '4' ||
                this.basicForm.receiveCompanyId == '5'
            ) {
                this.clientPop('err', '加工合同或事实合同原单')
                return
            }
            const linkData = {
                '1': '/contractDefinitionShow', //分包合同
                '2': '/processingContractApplyShow', //加工合同
                // '3': '/ctMaterialSalesSigningShow' //销售合同
                '3': '/ctMaterialSalesApplyShow' //销售合同
            }
            const data = linkData[this.basicForm.businessTypeKey]
            this.test = this.basicForm.contractId
            openAppClient(
                `${data}?billid=${this.basicForm.contractId}&isview=true`,
                '合同'
            )
        },
        businessTypeChenge (value) {
            this.basicForm.receiveCompanyName = ''
            this.basicForm.receiveCompanId = ''
            this.basicForm.contractName = ''
            this.basicForm.contractId = ''
            this.basicForm.receivePersonName = ''
            this.basicForm.receivePersonId = ''
            if(this.detailedTableData.length > 0) {
                this.detailedTableData[0].children.forEach(item=>item.changeType = -1)
            }
            this.basicForm.businessTypeValue = this.receiveBusinessType.find(
                x => x.id == value
            ).uname
            if(this.basicForm.businessTypeKey == 4 || this.basicForm.businessTypeKey == 5) this.basicForm.contractType = this.basicForm.businessTypeKey
        },
        onSave () {
            this.$Ajax
                .httpPost({
                    url: '/turnover/receive/update',
                    params: this.basicForm
                })
                .then(() => {
                    this.clientPop('suc', '修改成功', this.getBasicInfo)
                })
        },
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            showLoading()
            this.$Ajax
                .httpGet({
                    url: '/turnover/receive/delete',
                    params: { billId: this.billId },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    hideLoading()
                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },

        handleClose () {
            this.$router.push('/revolveReceiveList')
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject) => {
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        otherRequest
                            .turnoverReceiveUpdate(this.basicForm)
                            .then(() => {
                                this.getBasicInfo() //更新基本信息
                                resolve()
                            })
                            .catch(err => {
                                this.setError('baseInfo')
                                reject(err)
                            })
                    } else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            if (this.detailedTableData.length > 0) {
                this.detailedTableData[0].businessType =
                    this.basicForm.businessTypeKey
            }
            return new Promise((resolve, reject) => {
                this.verifyTable().then(() => {
                    otherRequest
                        .turnoverReceiveUpdateDtlList(this.detailedTableData)
                        .then(() => {
                            this.getDtlList() //更新明细
                            resolve()
                        })
                        .catch(err => {
                            this.setError('detailed')
                            reject(err)
                        })
                }).catch(() => {
                    this.setError('detailed')
                    reject()
                })
            })
        },
        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                ]
            }
            submitCommit(this, requestFn)
        },

        collectCount () {
            this.basicForm.receiveQuantity = null
            if (this.detailedTableData.length > 0) {
                this.detailedTableData.forEach(v => {

                    const count = v.children.reduce(
                        (prev, c) => (prev += Number(c.receivedQuantity) || 0),
                        0
                    ).toFixed(2)

                    this.basicForm.receiveQuantity = count
                    v.materialName = `小计： ${count}`
                })
            }
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.curRow = row
            if (row.changeType !== 1) {
                {
                    this.curRow.changeType = 2
                }
            }

            // 计算剩余库存数量
            if (row.receivedQuantity) {
                row.remainingInventory =
                    Number(row.inventoryQuantity - row.receivedQuantity).toFixed(2)
            }
            this.collectCount()
        },
        //点击删除的时候
        deleteEle (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    deleteLogic(row, $index, this, ['receiveQuantity'])
                }
            )
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            } else if (row.changeType === -1) {
                return 'row-hide'
            } else {
                return 'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //跳转到明细
        scorllDtl () {
            if (this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject) => {
                this.errorMsg = []
                this.detailedTableData.forEach(v => {
                    v.children.forEach((item, index) => {
                        if (item.changeType !== -1) {
                            if (
                                item.warehouseName === '' ||
                                item.warehouseName === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的仓库`
                                this.errorMsg.push(str)
                            }
                            if (
                                item.timeUnit === '' ||
                                item.timeUnit === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的计时单位`
                                this.errorMsg.push(str)
                            }
                            if (
                                item.usageTime === '' ||
                                item.usageTime === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的使用时间`
                                this.errorMsg.push(str)
                            }
                            if (
                                item.receivedQuantity === '' ||
                                item.receivedQuantity === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的领用数量`
                                this.errorMsg.push(str)
                            }
                            if (
                                item.pickingWarehouseName === '' ||
                                item.pickingWarehouseName === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的领用单位仓库`
                                this.errorMsg.push(str)
                            }

                            if (
                                item.supplyType === '' ||
                                item.supplyType === null
                            ) {
                                let str = `请填写第 ${index + 1} 行的甲供类型`
                                this.errorMsg.push(str)
                            }
                        }
                    })
                })

                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()
                } else {
                    this.isErrorMsg = false
                    resolve()
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
    color: red;
}

.like {
    color: rgb(46, 97, 215);
    font-size: 17px;
    line-height: 30px;
    cursor: pointer;
}
</style>
